package com.redBook.service.impl;

import com.redBook.constant.MessageConstant;
import com.redBook.context.BaseContext;
import com.redBook.dto.NoteCommentDTO;
import com.redBook.dto.NoteInfoDTO;
import com.redBook.dto.UserLoginDTO;
import com.redBook.entity.*;
import com.redBook.exception.LoginFailedException;
import com.redBook.mapper.*;
import com.redBook.result.PageResult;
import com.redBook.service.UserService;
import com.redBook.vo.NoteCommentVO;
import com.redBook.vo.NoteInfoVO;
import com.redBook.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryChildMapper categoryChildMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NotesInfoMapper notesInfoMapper;
    @Autowired
    private UserDetailMapper userDetailMapper;
    @Autowired
    private NoteDetailMapper noteDetailMapper;
    @Autowired
    private NotePictureMapper notePictureMapper;
    @Autowired
    private NoteCommentMapper noteCommentMapper;

    @Override
    public List<Category> getCategoryList() {
        List<Category> categoryList = categoryMapper.list();
        log.info("categoryList -> {}",categoryList);
        return categoryList;
    }

    @Override
    public List<CategoryChild> getCategoryChildList() {
        return categoryChildMapper.list();
    }

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String phone = userLoginDTO.getPhone();
        log.info("登录的手机号: {}",phone);
        UserLogin userLogin = userMapper.findByPhone(phone);
        if(userLogin != null){
            UserLoginVO userLoginVO = new UserLoginVO();
            userLoginVO.setId(userLogin.getId());
            userLoginVO.setPhone(userLogin.getPhone());
            return userLoginVO;
        }else{
            throw new LoginFailedException(MessageConstant.PHONE_IS_NOT_EXISTS);
        }
    }

    @Override
    public PageResult<NoteInfo> findNotesByPage(long startPage, long size) {
        List<NoteInfo> noteInfoList = notesInfoMapper.findNotesByPage(startPage,size);

        List<NoteInfoVO> noteInfoVOList = new ArrayList<>();
        List idList = new ArrayList();

        noteInfoList.forEach(id->{
            NoteInfoVO noteInfoVO = new NoteInfoVO();
            idList.add(id.getUId());
            BeanUtils.copyProperties(id,noteInfoVO);
            noteInfoVOList.add(noteInfoVO);
        });

        log.info("idList -> {}",idList);

        List<UserDetail> byUserIdList = userDetailMapper.findByUserIdList(idList);

        byUserIdList.forEach(user -> {
            noteInfoVOList.forEach(noteInfo -> {
                if(user.getUserId().equals(noteInfo.getUId())){
                    noteInfo.setNickname(user.getNickname());
                    noteInfo.setHeadImage(user.getHeadImage());
                }
            });
        });

        PageResult pageResult = new PageResult();
        pageResult.setSize(size);
        pageResult.setStartPage(startPage);
        pageResult.setTotal(noteInfoVOList.size());
        pageResult.setRecords(noteInfoVOList);
        return pageResult;
    }

    @Override
    public UserDetail findUserById(Long uid) {
        UserDetail userDetail = userDetailMapper.findByUserId(uid);
        switch (userDetail.getSex()) {
            case 1:
                userDetail.setGender("男");
                break;
            case 2:
                userDetail.setGender("女");
                break;
            default:
                userDetail.setGender("未知");
                break;
        }
        return userDetail;
    }

    @Override
    public NoteDetail noteDetail(Long noteId) {
        NoteDetail noteDetail = noteDetailMapper.findByNoteId(noteId);
        log.info("noteDetail->{}", noteDetail);
        if (noteDetail != null) {
            // 使用 CompletableFuture 并行化获取数据
            CompletableFuture<List<NotePicture>> notePictureFuture = CompletableFuture.supplyAsync(() -> notePictureMapper.findByNoteId(noteId));
            CompletableFuture<NoteInfo> noteInfoFuture = CompletableFuture.supplyAsync(() -> notesInfoMapper.findByNoteId(noteId));
            CompletableFuture<UserDetail> userDetailFuture = CompletableFuture.supplyAsync(() -> userDetailMapper.findByUserId(noteInfoFuture.join().getUId()));
            CompletableFuture<List<NoteCommentVO>> noteCommentListFuture = CompletableFuture.supplyAsync(() -> noteCommentMapper.findByNoteId(noteId));

            // 等待所有任务完成
            CompletableFuture.allOf(notePictureFuture, noteInfoFuture, userDetailFuture, noteCommentListFuture).join();

            // 获取异步任务结果
            List<NotePicture> notePictureList = notePictureFuture.join();
            NoteInfo noteInfo = noteInfoFuture.join();
            UserDetail userDetail = userDetailFuture.join();
            List<NoteCommentVO> noteCommentList = noteCommentListFuture.join();

            if (!noteCommentList.isEmpty()) {
                List<NoteCommentVO> noteCommentList2 = new ArrayList<>();
                noteCommentList.forEach(comment -> {
                    if (comment.getParentId() != 0) {
                        noteCommentList2.add(comment);
                        noteCommentList.remove(comment);
                    }
                });

                noteCommentList.forEach(comment -> {
                    List<NoteCommentVO> noteCommentListChild = new ArrayList<>();
                    noteCommentList2.forEach(comment2 -> {
                        if (comment.getId() == comment2.getParentId()) {
                            noteCommentListChild.add(comment2);
                        }
                    });
                    comment.setChildComment(noteCommentListChild);
                    noteCommentListChild.clear();
                });
            }

            // 设置 NoteDetail
            noteDetail.setNickname(userDetail.getNickname());
            noteDetail.setHeadImage(userDetail.getHeadImage());
            noteDetail.setLikes(noteInfo.getLikes());
            noteDetail.setTitle(noteInfo.getTitle());
            noteDetail.setUpdateTime(noteInfo.getUpdateTime());
            noteDetail.setNotePictureList(notePictureList);
            noteDetail.setIsFollow(BaseContext.getCurrentId() == noteDetail.getUId());
            noteDetail.setNoteCommentVOList(noteCommentList);

            return noteDetail;
        } else {
            return null;
        }
        /**
         * @龚英杰 20250308
         * 20250308之前
         *
         * NoteDetail noteDetail = noteDetailMapper.findByNoteId(noteId);
         *         log.info("noteDetail->{}",noteDetail);
         *         if(noteDetail != null){
         *             List<NotePicture> notePictureList = notePictureMapper.findByNoteId(noteId);
         *             NoteInfo noteInfo = notesInfoMapper.findByNoteId(noteId);
         *             UserDetail userDetail = userDetailMapper.findByUserId(noteInfo.getUId());
         *             List<NoteCommentVO> noteCommentList = noteCommentMapper.findByNoteId(noteId);
         *             if(!noteCommentList.isEmpty()){
         *                 List<NoteCommentVO> noteCommentList2 = new ArrayList<>();
         *                 noteCommentList.forEach(comment -> {
         *                     if(comment.getParentId() != 0){
         *                         noteCommentList2.add(comment);
         *                         noteCommentList.remove(comment);
         *                     }
         *                 });
         *
         *                 noteCommentList.forEach(comment->{
         *                     List<NoteCommentVO> noteCommentListChild = new ArrayList<>();
         *                     noteCommentList2.forEach(comment2 ->{
         *                         if(comment.getId() == comment2.getParentId()){
         *                             noteCommentListChild.add(comment2);
         *                         }
         *                     });
         *                     comment.setChildComment(noteCommentListChild);
         *                     noteCommentListChild.clear();
         *                 });
         *             }
         *             noteDetail.setNickname(userDetail.getNickname());
         *             noteDetail.setHeadImage(userDetail.getHeadImage());
         *             noteDetail.setLikes(noteInfo.getLikes());
         *             noteDetail.setTitle(noteInfo.getTitle());
         *             noteDetail.setUpdateTime(noteInfo.getUpdateTime());
         *             noteDetail.setNotePictureList(notePictureList);
         *             noteDetail.setIsFollow(BaseContext.getCurrentId() == noteDetail.getUId()?true:false);
         *             noteDetail.setNoteCommentVOList(noteCommentList);
         *             return noteDetail;
         *         }else{
         *             return null;
         *         }
         */
    }
    @Override
    public void addNote(List<String> pathList,
                        Long uid,
                        String title,
                        String context,
                        String power,
                        String address,
                        List<Long> height,
                        List<Long> width) {

        NoteInfoDTO noteInfoDTO = new NoteInfoDTO();
        noteInfoDTO.setTitle(title);
        noteInfoDTO.setUid(uid);
        noteInfoDTO.setCover(pathList.get(0));
        noteInfoDTO.setWidth((long) (width.get(0)));
        noteInfoDTO.setHeight((long) (height.get(0)));

        log.info(pathList.get(0));
        notesInfoMapper.saveNote(noteInfoDTO);
        noteDetailMapper.saveNote(noteInfoDTO.getId(),context,power);
        notePictureMapper.savePicture(pathList,noteInfoDTO.getId(),height,width);

    }

    @Override
    public void submitComment(NoteCommentDTO noteCommentDTO) {
        noteCommentMapper.submitComment(noteCommentDTO);
    }

    @Override
    public PageResult<NoteInfo> findNotesByPageAndUser(long startPage, long size, Long userId) {
        List<NoteInfo> noteInfoList = notesInfoMapper.findNotesByPageAndUser(startPage,size,userId);

        List<NoteInfoVO> noteInfoVOList = new ArrayList<>();
        List idList = new ArrayList();

        noteInfoList.forEach(id->{
            NoteInfoVO noteInfoVO = new NoteInfoVO();
            idList.add(id.getUId());
            BeanUtils.copyProperties(id,noteInfoVO);
            noteInfoVOList.add(noteInfoVO);
        });

        log.info("idList -> {}",idList);

        List<UserDetail> byUserIdList = userDetailMapper.findByUserIdList(idList);

        byUserIdList.forEach(user -> {
            noteInfoVOList.forEach(noteInfo -> {
                if(user.getUserId().equals(noteInfo.getUId())){
                    noteInfo.setNickname(user.getNickname());
                    noteInfo.setHeadImage(user.getHeadImage());
                }
            });
        });

        PageResult pageResult = new PageResult();
        pageResult.setSize(size);
        pageResult.setStartPage(startPage);
        pageResult.setTotal(noteInfoVOList.size());
        pageResult.setRecords(noteInfoVOList);
        return pageResult;
    }
}
